
import matplotlib.pyplot as plt
import re
import numpy as np
import setting

def C(c, x):
	rou = x/c
	A = np.math.factorial(c)/((c*rou)**c)
	B = sum((c*rou)**k/np.math.factorial(k) for k in range(c))
	return 1/(1+ (1-rou)*A*B)

def MMC(c,la,mu):
	return C(c,la/mu)/(c*mu-la)+1/mu

def parse_result(path):
	f=open(path)
	lines = f.readlines()
	f.close()
	ts = []
	for line in lines:
		mat = re.match("operation number=(.+)?",line)
		if mat:
			opnumber = int(mat.groups()[0])
			ts.append(opnumber)
	for line in lines:
		mat = re.match("average time=(.+)?",line)
		if mat:
			averagetime = float(mat.groups()[0])
			ts.append(averagetime)
	return ts


def get_data(prefix="partial-200-0.05"):
	ret =[[],[]]
	for i in np.arange(0.2,2.1,0.2):
		ts = parse_result("result//20180730//%s-%0.1f.txt"%(prefix,i))
		ret[0].append(ts[0])
		ret[1].append(ts[1])
	return ret


partial_prefix = "partial-200-0.2"
sequ_prefix = "sequ-200-0.2"

partial = get_data(partial_prefix)
sequ = get_data(sequ_prefix)



lam = np.arange(0.2,2.1,0.2)

width=2.8
height=3.0*2.6/4

fig = plt.gcf()
fig.set_size_inches(width,height)

# def cacl(a,b):
# 	return (a-b)/float(a)

# print(cacl([0][9],partial[0][9]))
# print(cacl([1][9],partial[1][9]))

plt.plot(lam,sequ[0],"r.-",label="Sequential")
plt.plot(lam,partial[0],"b^-",label=setting.system_name)
plt.xlabel("$\lambda$ ($s^{-1}$)")
plt.ylabel("Operation Number")
plt.grid(linestyle='--')
plt.legend()
plt.show()

# fig.savefig("figs/operation-number.pdf",dpi=400,bbox_inches="tight")

plt.clf()

height-=0.16

# fig = plt.gcf()
# fig.set_size_inches(width,height)
mu = 0.2+1.0/sequ[1][0]
lam1 = np.arange(0.2,mu,0.02)
y = 1/(mu - lam1)
print(y)
plt.plot(lam1,y,"g-",label="M/M/1")



plt.plot(lam,sequ[1],color='coral',marker='.' ,linestyle="--" ,label="Sequential")

plt.plot(lam,partial[1],color=setting.colors[0.2],marker=setting.markers[0.2],label=setting.system_name)



mu = 1.0/sequ[1][0]
lam1 = np.arange(0.2,2.2,0.02)
y = [MMC(20,la,mu) for la in lam1]
print(y)
plt.plot(lam1,y,"r-.",label="M/M/C")

plt.xlabel("$\lambda$ ($s^{-1}$)")
plt.ylabel("Time (s)")

# ax = plt.gca()
# nnn = np.linspace(0.5,2.5,5)
# ax.set_yticks(nnn)
# la = [str(a) for a in nnn]
# ax.set_yticklabels(la)
plt.grid(linestyle='--')
plt.legend()
plt.show()
# fig.savefig("figs/averagetime.pdf",dpi=400,bbox_inches="tight")
